/*
 * Copyright (c) 2025 CAX Conversion Project
 */
package com.comac.ins.isfd.util;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.comac.ins.common.core.constant.CommonConstant;
import com.comac.ins.common.core.exception.base.BaseException;
import com.comac.ins.common.core.utils.StringUtils;
import com.comac.ins.isfd.domain.bo.IsfdModelManagementTaskBdfDownLoadBo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Slf4j
public class FileUtils {
    public static void copyOrMoveFile(String oldIndexPath, String newIndexPath, Boolean isMove) {
        // 将字符串路径转换为Path对象
        Path source = Paths.get(oldIndexPath);
        Path destination = Paths.get(newIndexPath);

        // 检查源文件是否存在
        if (!Files.exists(source)) {
            throw new BaseException("源文件不存在！");
        }
        try {
            // 获取目标文件的父目录
            Path targetParent = destination.getParent();
            if (targetParent != null && !Files.exists(targetParent)) {
                Files.createDirectories(targetParent);
            }

            if (isMove) {
                // 如果 isMove 为 true，则执行文件移动
                Files.move(source, destination, StandardCopyOption.REPLACE_EXISTING);
            } else {
                // 如果 isMove 为 false，则执行文件拷贝
                Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
            }
        } catch (IOException e) {
            log.error("文件操作失败", e);
            throw new BaseException("文件操作失败！");
        }
    }


    /**
     * 项目根路径创建缓冲区来实现这个转换
     */
    public static File multiPartFileToFile(MultipartFile multipartFile) {
        File tempFile = null;
        try {
            //获取文件名
            String originalFilename = multipartFile.getOriginalFilename();

            //获取默认定位到的当前用户目录("user.dir"),也就是当前应用的根路径
            String tempDir = System.getProperty("user.dir");

            //获取文件名
            String fileName = StringUtils.substringBeforeLast(originalFilename, ".");
            //获取文件后缀
            String fileExt = StringUtils.substringAfterLast(originalFilename, ".");

            if (StringUtils.isBlank(fileName)) {
                throw new BaseException("导入的压缩包文件名不能为空！");
            }

            // 确保前缀长度至少为3
            if (fileName.length() < 3) {
                fileName = "tmp" + fileName; // 添加一个前缀以确保长度足够
            }

            //在项目根路径生成临时文件
            tempFile = File.createTempFile(fileName, "." + fileExt, new File(tempDir));

            multipartFile.transferTo(tempFile);

        } catch (Exception e) {
            log.error("multipartFile to file is fail .", e);
            throw new BaseException("multipartFile to file is fail .");
        } finally {
            //在jvm退出时执行删除此路径下的文件
            if (tempFile != null) {
                tempFile.deleteOnExit();
            }
        }
        return tempFile;
    }


    /**
     * 创建zip包，给zip包新增零件文件，必备件，边界条件，载荷文件和索引文件
     */
    public static void addPartAndIndexFileToZip(ZipOutputStream zos,
                                                IsfdModelManagementTaskBdfDownLoadBo downLoadBo,
                                                List<File> indexFileList) throws IOException {
        // 零件
        List<String> partPaths = downLoadBo.getPartPaths();
        String partPrePath = downLoadBo.getPartPrePath();
        if (CollectionUtils.isNotEmpty(partPaths)) {
            for (String partPath : partPaths) {
                // 磁盘路径
                String filePath = partPrePath + downLoadBo.getBatchNumber() + "/" + partPath;
                File file = new File(filePath);
                if (!file.exists()) {
                    log.error("零件文件不存在，filePath是：{}", filePath);
                    continue;
                }

                byte[] bytes = Files.readAllBytes(file.toPath());
                // zip的路径
                ZipEntry zipEntry = new ZipEntry(partPath);
                zos.putNextEntry(zipEntry);

                zos.write(bytes);
                zos.closeEntry();
            }
        }

        // 必备件
        List<IsfdModelManagementTaskBdfDownLoadBo.NecessaryItems> necessaryItemsList = downLoadBo.getNecessaryItemsList();
        if (CollectionUtils.isNotEmpty(necessaryItemsList)) {
            for (IsfdModelManagementTaskBdfDownLoadBo.NecessaryItems necessaryItems : necessaryItemsList) {
                String indexPath = necessaryItems.getIndexPath();
                // 磁盘路径
                String filePath = necessaryItems.getDiskPath();
                File file = new File(filePath);
                if (!file.exists()) {
                    log.error("必备件文件不存在，filePath是：{}", filePath);
                    continue;
                }

                byte[] bytes = Files.readAllBytes(file.toPath());
                // zip的路径
                ZipEntry zipEntry = new ZipEntry(indexPath);
                zos.putNextEntry(zipEntry);

                zos.write(bytes);
                zos.closeEntry();
            }
        }

        // 边界条件
        List<String> boundaryPaths = downLoadBo.getBoundaryPaths();
        String boundaryExportPath = downLoadBo.getBoundaryExportPath();
        if (CollectionUtils.isNotEmpty(boundaryPaths)) {
            for (String boundaryPath : boundaryPaths) {
                // 磁盘路径
                File file = new File(boundaryPath);
                if (!file.exists()) {
                    log.error("边界条件文件不存在，filePath是：{}", boundaryPath);
                    continue;
                }

                byte[] bytes = Files.readAllBytes(file.toPath());
                // zip的路径
                ZipEntry zipEntry = new ZipEntry(boundaryExportPath + "/" + file.getName());
                zos.putNextEntry(zipEntry);
                zos.write(bytes);
                zos.closeEntry();
            }
        }

        // 载荷文件
        List<String> loadPaths = downLoadBo.getLoadPaths();
        String loadExportPath = downLoadBo.getLoadExportPath();
        if (CollectionUtils.isNotEmpty(loadPaths)) {
            for (String loadPath : loadPaths) {
                // 磁盘路径
                File file = new File(loadPath);
                if (!file.exists()) {
                    log.error("载荷文件不存在，filePath是：{}", loadPath);
                    continue;
                }

                byte[] bytes = Files.readAllBytes(file.toPath());
                // zip的路径
                ZipEntry zipEntry = new ZipEntry(loadExportPath + "/" + file.getName());
                zos.putNextEntry(zipEntry);

                zos.write(bytes);
                zos.closeEntry();
            }
        }

        // 非标文件
        List<String> nonstandardPaths = downLoadBo.getNonstandardPaths();
        String nonstandardExportPath = downLoadBo.getNonstandardExportPath();
        if (CollectionUtils.isNotEmpty(nonstandardPaths)) {
            for (String nonstandardPath : nonstandardPaths) {
                // 磁盘路径
                File file = new File(nonstandardPath);
                if (!file.exists()) {
                    log.error("非标文件不存在，filePath是：{}", nonstandardPath);
                    continue;
                }

                byte[] bytes = Files.readAllBytes(file.toPath());
                // zip的路径
                ZipEntry zipEntry = new ZipEntry(nonstandardExportPath + "/" + file.getName());
                zos.putNextEntry(zipEntry);

                zos.write(bytes);
                zos.closeEntry();
            }
        }

        if (CollectionUtils.isNotEmpty(indexFileList)) {
            for (File indexFile : indexFileList) {
                // 索引文件
                if (indexFile != null && indexFile.exists()) {
                    Path indexFilePath = indexFile.toPath();
                    byte[] indexBytes = Files.readAllBytes(indexFilePath);
                    String zipPath = indexFilePath.toString();
                    zipPath = zipPath.replace("\\", "/");
                    if (zipPath.startsWith("/")) {
                        zipPath = zipPath.substring(1);
                    }
                    ZipEntry indexZipEntry = new ZipEntry(zipPath);
                    zos.putNextEntry(indexZipEntry);

                    zos.write(indexBytes);
                    zos.closeEntry();
                }
            }
        }

    }

    /**
     * 生成索引文件
     */
    public static File writeIndexFile(List<String> list, String filePath) throws IOException {
        Path path = Paths.get(filePath);
        if (!Files.exists(path.getParent())) {
            Files.createDirectories(path.getParent());
        }
        File file = new File(filePath);
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
            for (String line : list) {
                writer.write(CommonConstant.INCLUDE + "'" + line + "'");
                writer.newLine(); // 写入换行符
            }
            // 在所有元素写入后，单独写入'$'
            if (!list.isEmpty()) { // 确保列表不为空时才添加'$'
                writer.write("$");
            }
        }
        return file;
    }
}
